﻿using AutoMapper;
using D.B.Data.API.Applications.Command.RoleCommand;
using D.B.Data.Domain;
using D.B.Data.Domain.DTO.Output;
using D.B.Data.ErrorCode;
using D.B.Data.Infrastructuse;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace D.B.Data.API.Applications.CommandHandler.RoleCommandHandler
{
    public class GiveRoleGetUserCommandHandler : IRequestHandler<GiveRoleGetUserCommand, APIResult<List<GiveRoleGetUserOutput>>>
    {
        private readonly IBaseRepository<UserRoleModel> baseRepository;
        private readonly IBaseRepository<UserModel> userRepository;
        private readonly IMapper mapper;

        public GiveRoleGetUserCommandHandler(IBaseRepository<UserRoleModel> baseRepository, IMapper mapper, IBaseRepository<UserModel> userRepository)
        {
            this.baseRepository = baseRepository;
            this.mapper = mapper;
            this.userRepository = userRepository;
        }

        public Task<APIResult<List<GiveRoleGetUserOutput>>> Handle(GiveRoleGetUserCommand request, CancellationToken cancellationToken)
        {
            var res = baseRepository.GetAll().AsNoTracking().Where(s => s.RoleId == request.RoleId).Select(s => s.UserId);

            var Userlist = userRepository.GetAll().AsNoTracking().Where(s => res.Contains(s.Id));

            var model = mapper.Map<List<GiveRoleGetUserOutput>>(Userlist);

            APIResult<List<GiveRoleGetUserOutput>> result = new APIResult<List<GiveRoleGetUserOutput>>()
            {
                Code = EnumCode.Ok,
                Msg = "显示成功",
                Data= model

            };
            return Task.FromResult(result);




        }
    }
}
